package ssi.actions;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

import ssi.tools.Connector;
import ssi.tools.SendEmail;
import ssi.beans.User;

public class AdoptionAction extends Action {
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		request.setCharacterEncoding("UTF-8");		
		HttpSession session = request.getSession(true);
		User user = (User)session.getAttribute("user");
		User users=(User)form;
		String userID =  String.valueOf(user.getId());
		String animalID=users.getAnimalID();

		System.out.println("AnimalID: "+ animalID);
		String query = "SELECT COUNT(*) FROM `adoption` WHERE `AnimalId`='"+animalID+"'";
		String target=null;
		ActionErrors actionErrors = new ActionErrors();
		try{
			Connection connection = new Connector().getConnection();
    		Statement statement = connection.createStatement();
    		ResultSet rs = statement.executeQuery(query);
    		rs.next();
    		System.out.println(query);
    		if(rs.getInt("COUNT(*)")==0){
    			query = "INSERT INTO `adoption`(`date`, `adoptionFee`, `customerId`, `AnimalId`, `confirmation`) VALUES('0000-00-00', 40,"+userID+","+animalID+",\""+DigestUtils.md5Hex(userID+animalID)+"\")";
    			System.out.println(query);
    			statement.executeUpdate(query);
    			statement.executeUpdate("UPDATE animals SET adopted=1 where id='"+animalID+"'");
    			new SendEmail().sendAdoptionEmail(user.getEmail(),DigestUtils.md5Hex(userID+animalID));
    			target="success";
    		
    			connection.close();
    		} else{
    			actionErrors.add("error",
    					new ActionMessage("error.AdoptionError"));
    			target="failure";
    		}
		} catch(Exception e){
			e.printStackTrace();
			target="failure";
			actionErrors.add("error",
					new ActionMessage("error.catch"));
		}
		
		if(actionErrors.size() !=0){
			extracted(request, actionErrors);
			return new ActionForward(mapping.getInput());
		}

		return mapping.findForward(target);
	}
	
	private void extracted(HttpServletRequest request, ActionErrors actionErrors) {
		saveErrors(request, actionErrors);
	}

}
